
(function(root) {
    'use strict';

    //扩展帮助方法
    var helper = {};

    // 唯一标示 uuid
    helper.uuid = function() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    };

    // 得到cookie
    helper.getCookie = function(name) {
        var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
        if(arr= document.cookie.match(reg)){
            return unescape(arr[2]);
        } else {
            return null;
        }
    };

    helper.setCookie = function(name, value, time) {
        if(time) {
            document.cookie = name + "=" + escape(value) + ";expires=" + time;
        } else {
            document.cookie = name + "=" + escape(value) + ";";
        }
    };

    //遍历
    /**
     * @method each
     * @parame loopable 要遍历的对象
     * @parame callback 回调函数
     * @parame self 上下文
     **/
    helper.each = function(loopable, callback, self) {
        var additionalArgs = Array.prototype.slice.call(arguments,3);
        if(loopable) {
            if(loopable.length === +loopable.length) {
                var i;
                for(var i=0; i<loopable.length; i++) {
                    callback.apply(self, [loopable[i],i].concat(additionalArgs));
                }
            } else {
                for(var item in loopable) {
                    callback.apply(self, [loopable[item], item].concat(additionalArgs));
                }
            }
        }
    };

    //扩展
    /**
     *@method extend
     *@parame base 要扩展的对象
     *@return base  返回扩展后的对象
     **/
    helper.extend = function(base) {
        helper.each(Array.prototype.slice.call(arguments, 1), function(extensionObject) {
            helper.each(extensionObject, function(value, key) {
                if(extensionObject.hasOwnPrototype(key)) {
                    base[key] = value;
                }
            });
        });
        return base;
    };

    //返回数组元素所在的位置，确定是否包含在里面
    /**
     *@method indexOf
     *@parame arrayToSearch 查找的对象
     *@parame item 查找的元素
     *@return args  返回位置
     **/
    helper.indexOf = function(arrayToSearch,item){
        if(Array.prototype.indexOf){
            return arrayToSearch.indexOf(item);
        } else {
            for(var i=0; i< arrayToSearch.length; i++){
                if(arrayToSearch[i] == item) return i;
            }
            return -1;
        }
    };

    // 绑定事件
    helper.on = function(target, type, handler) {
        if(target.addEventListener) {
            target.addEventListener(type, handler, false);
        } else {
            target.attachEvent("on" + type,
                function(event) {
                    return handler.call(target, event);
                }, false);
        }
    };

    // 签名
    helper.sign = function(obj) {
        obj = helper.changeJSON2Query(obj)
        obj = helper.sort(obj)
        obj = obj.join('&')
        obj = hex_md5(obj).toLocaleUpperCase()
        return obj;
    };

    helper.changeJSON2Query =  function (jsonObj) {
        var args = '';
        for (var i in jsonObj) {
            if (typeof jsonObj[i] != "object" && i != 'userAgent' && i != 'sign') {
                if (args != '') {
                    args += '&';
                }
                args += i + '=' + encodeURIComponent(jsonObj[i]);
            }
        }
        return args;
    };

    helper.sort = function(str) {
        var strArr=str.split('&');
        var s1 = Array.prototype.sort.call(strArr,function(a,b){
            for(var i=0; i<a.length;i++){
                if(a.charCodeAt(i)==b.charCodeAt(i)) continue;
                return a.charCodeAt(i) - b.charCodeAt(i);
            }
        });
        return s1;
    };

    // 请求，保存数据
    helper.send = function(obj, url) {
        //签名
        obj.sign = helper.sign(obj)
        if (window.XMLHttpRequest) {
            var xhr = new XMLHttpRequest();
        } else {
            var xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xhr.open('POST', url)
        xhr.setRequestHeader('Content-Type', 'application/json')
        xhr.withCredentials = false;
        xhr.send(JSON.stringify(obj))
    };

    // 监听页面所有ajax请求
    /**
     * @parames {function} callback 回调
     */
    helper.listenAjax = function(callback) {
        var open = window.XMLHttpRequest.prototype.open;
        var send = window.XMLHttpRequest.prototype.send;
        var openReplacement = function(method,url) {
            open.apply(this, arguments);
        };

        var readystatechangeReplacement = function() {
            if(this.readyState === 4 && this.status === 200) {
                callback && callback(this);
            }
        };
        var sendReplacement = function() {
            var that = this;
            send.apply(this, arguments);
            setTimeout(function() {
                that.onreadystatechange = readystatechangeReplacement;
            },0);
        };
        window.XMLHttpRequest.prototype.open = openReplacement;
        window.XMLHttpRequest.prototype.send = sendReplacement;
    };

    //获取域名
    helper.getDomainName = function() {
        return 'https://scrm.stccs.com.cn';
    }

    var collect = {};
    var host = window.location.host;

    collect.parmas = {};
    collect.url = helper.getDomainName()+'/api/setPoint';
    collect.uuid = helper.uuid();

    collect.setParames = function() {
        if(document) {
            this.parmas.domain = document.domain || '';
            this.parmas.url = document.URL || '';
            this.parmas.title = document.title || '';
            this.parmas.referrer = document.referrer;
        }
        if(window && window.screen) {
            this.parmas.sh = window.screen.height || 0;
            this.parmas.sw = window.screen.width || 0;
            this.parmas.cd = window.screen.colorDepth || 0;
        }
        if (navigator) {
            this.parmas.lang = navigator.language || '';
            this.parmas.userAgent = navigator.userAgent || '';
        }
        this.parmas.target = [];
        this.parmas.uuid = collect.uuid;
        if(helper.getCookie('_ST_userAccect')) {
            this.parmas.uuid = helper.getCookie('_ST_userAccect');
        }
        //登录用户
        if(helper.getCookie('member_token')) {
            this.parmas.member_token = helper.getCookie('member_token');
        }
        //解析 配置项
        if(typeof _ST != "undefined") {
            for(var i in _ST) {
                switch(_ST[i][0]) {
                    case 'Target':
                        this.parmas.target = _ST[i].slice(1);
                        break;
                    default:
                        break;
                }
            }
            if(_ST.syserror && _ST.syserror.length) {
                this.parmas.syserror = _ST.syserror;
                _ST.syserror = [];
            } else {
                delete this.parmas.syserror;
            }
            // 扩展参数
            if(_ST.extendParams) {
                for(var k in _ST.extendParams) {
                    if(_ST.extendParams.hasOwnProperty(k)) {
                        this.parmas[k] = _ST.extendParams[k]
                    }
                }
            }
        } else {
            throw "必须定义全局配置变量 _ST，配置指定的请求Url。示例： var _ST = _ST || []; _ST.push(['Url','127.0.0.1/users?']);";
        }
    };

    collect.getParames = function() {
        return this.parmas;
    };

    // 用户的停留时间
    collect.timer = function() {
        this.disp = new Date().getTime();
    };

    collect.event = function() {
        var that = this;
        helper.on(document.body,'click', function(e) {


            var $target = e.target || e.srcElement;
            console.log($target);
            var currtagName = $target.nodeName.toLowerCase();
            if(currtagName == "body" || currtagName == "html" || currtagName == "") {
                return 0;
            }

            var Id = $target.getAttribute('id')
            var Class = $target.getAttribute('class')
            var ClassArr = []
            if(Class) {
                Class = Class.split(' ')
                for(var i=0; i< Class.length; i++){
                    ClassArr.push('.'+Class[i])
                }
            }
            let clssInt = that.parmas.target.filter(function (val) { return ClassArr.indexOf(val) > -1 })
            console.log(that.parmas.target);

            if(helper.indexOf(that.parmas.target, currtagName) > -1 || helper.indexOf(that.parmas.target, '#'+Id) > -1 || clssInt.length > 0) {
                if(!helper.getCookie('_ST_userAccect')) {
                    // 初次进入网站，返回用户凭证。
                    helper.setCookie('_ST_userAccect', that.uuid);
                }
                //id标签
                var attrId = $target.getAttribute('id');
                if(attrId) {
                    that.parmas.collectId = '#'+attrId;
                } else {
                    delete that.parmas.collectId;
                }
                //class标签
                if(clssInt.length > 0) {
                    that.parmas.collectClass = clssInt.join(' ');
                } else {
                    delete that.parmas.collectClass;
                }
                var click = {
                    nodeName:$target.nodeName,
                    title:$target.title,
                    text:$target.innerHTML,
                };
                that.parmas.clickElement = click;
                that.parmas.point_id = $target.getAttribute('pointId');
                that.setParames();
                helper.send(that.getParames(), that.url);
            }
        });

        // 用户离开页面时返回逗留时间
        // window.onbeforeunload = function(evt){
        //     that.parmas.disp = new Date().getTime() - that.disp;
        //     if(!helper.getCookie('_ST_userAccect')) {
        //         helper.setCookie('_ST_userAccect', that.uuid);
        //     }
        //     delete that.parmas.collectId;
        //     delete that.parmas.collectClass;
        //     delete that.parmas.clickElement;
        //     that.setParames();
        //     helper.send(that.getParames(), that.url);
        // };
    };

    collect.init = function() {
        var that = this;
        that.timer();
        that.event();
        that.setParames();
        if(!helper.getCookie('_ST_userAccect')) {
            helper.setCookie('_ST_userAccect', that.uuid);
        }
        // helper.send(that.getParames(), that.url);
        delete that.parmas.syserror;
    };

    collect.init();

})(window);
